package org.example.zuul;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import sun.net.util.IPAddressUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/9/8.
 */
@Slf4j
public class IpFilter extends ZuulFilter {
    private List<String> blackIpList = Arrays.asList("127.0.0.1");

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        String ip = currentContext.getRequest().getRemoteAddr();
        String token = currentContext.getRequest().getHeader("Authorization");
        //
        if (log.isDebugEnabled()) {
            log.debug("ip:{}", ip);
            log.debug(currentContext.getRequest().getLocalAddr());
            log.debug(currentContext.getRequest().getLocalName());
            log.debug(currentContext.getRequest().getRemoteHost());
        }
        if(!StringUtils.isEmpty(ip) && this.blackIpList.contains(ip)) {
            currentContext.setSendZuulResponse(false);
            HashMap<String, String> result = new HashMap<>();
            ObjectMapper objectMapper = new ObjectMapper();
            result.put("code","401");
            result.put("msg","非法请求");
            try {
                currentContext.setResponseBody(objectMapper.writeValueAsString(result));
                currentContext.getResponse().setContentType("application/json;charset=UTF-8");
            } catch (JsonProcessingException e) {
                log.error("转换json格式异常", e);
            }
        }
        return null;
    }
}
